package com.cwits.wifi.ui.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.cwits.wifi.R;
import com.cwits.wifi.base.BaseActivity2;
import com.cwits.wifi.util.TimeFormater;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXFileObject;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class VideoActivity extends BaseActivity2 implements View.OnClickListener, SurfaceHolder.Callback {

    private String mVideoPath;
    private MediaPlayer player;
    //private SurfaceView surface;
    private SurfaceHolder surfaceHolder;
    private boolean isPlay = true;
    private SeekBar mSeekBar;
    private ImageView mImBack;
    private ImageView mImPlay;
    private TextView mTvTime1, mTvTime2;
    private RelativeLayout mRlDel, mRlShare, mRlPho;
    private LinearLayout mLlShareWx, mLlShare;
    private Button mBtnCancle;
    private static final String APP_ID = "wx25f4c929710a4976";
    private IWXAPI api;
    public static int WXSceneSession = 0;
    //计时器
    private Timer timer;
    //任务
    private TimerTask task;

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                ConnectivityManager mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo netInfo = mConnectivityManager.getActiveNetworkInfo();
                if (netInfo != null && netInfo.isAvailable()) {

                    ///////网络连接
                } else {
                    ////////网络断开

                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video);
        init();
    }


    private void init() {
        api = WXAPIFactory.createWXAPI(this, APP_ID, true);
        api.registerApp(APP_ID);
        Intent intent = getIntent();
        mVideoPath = intent.getStringExtra("video_file");
        mLlShare = (LinearLayout) findViewById(R.id.video_activity_ll_share);
        mLlShareWx = (LinearLayout) findViewById(R.id.video_activity_ll_share_wx);
        mBtnCancle = (Button) findViewById(R.id.video_activity_btn_cancle);
        mLlShareWx.setOnClickListener(this);
        mBtnCancle.setOnClickListener(this);

        mSeekBar = (SeekBar) findViewById(R.id.video_activity_seekbar);
        mImBack = (ImageView) findViewById(R.id.video_activity_im_back);
        mRlDel = (RelativeLayout) findViewById(R.id.video_activity_rl_del);
        mRlShare = (RelativeLayout) findViewById(R.id.video_activity_rl_share);
        mRlPho = (RelativeLayout) findViewById(R.id.video_activity_rl_pho);
        mRlShare.setOnClickListener(this);
        mRlPho.setOnClickListener(this);
        mImBack.setOnClickListener(this);
        mRlDel.setOnClickListener(this);
        mTvTime1 = (TextView) findViewById(R.id.video_activity_tv_time1);
        mTvTime2 = (TextView) findViewById(R.id.video_activity_tv_time2);
        mImPlay = (ImageView) findViewById(R.id.video_activity_im_play);
        //surface = (SurfaceView) findViewById(R.id.surface);
        //surfaceHolder = surface.getHolder();//SurfaceHolder是SurfaceView的控制接口
        surfaceHolder.addCallback(this); //因为这个类实现了SurfaceHolder.Callback接口，所以回调参数直接this
        //surfaceHolder.setFixedSize(320, 220);//显示的分辨率,不设置为视频默认
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);//Surface类型


        mImPlay.setOnClickListener(this);
        if (mApplication.getIsOffLineMode() == false) {
            disconnectDevice();
            mApplication.setIsOffLineMode(true);
            mApplication.setRealCamera(false);
            mApplication.setIsNeedReconnect(true);
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mReceiver, filter);
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                stopTimer();

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                player.seekTo(seekBar.getProgress());
                startTimer();

            }
        });

        /*timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                //每隔1秒钟执行一下run方法
                int max = player.getDuration();
                mSeekBar.setMax(max);
                int progress = player.getCurrentPosition();
                System.out.println("progress" + progress);
                mSeekBar.setProgress(progress);
            }
        };*/
    }

    public static Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);  ///把流转化为Bitmap图片

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    public void deleteFile() {
        File dirFile = new File(mVideoPath);
        if (!dirFile.exists()) {
            return;
        }
        if (dirFile.isDirectory()) {
            String[] children = dirFile.list();
            for (int i = 0; i < children.length; i++) {
                new File(dirFile, children[i]).delete();
            }
        }

        dirFile.delete();
    }

    public void deleteFilePho(String path) {
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            return;
        }
        if (dirFile.isDirectory()) {
            String[] children = dirFile.list();
            for (int i = 0; i < children.length; i++) {
                new File(dirFile, children[i]).delete();
            }
        }

        dirFile.delete();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.video_activity_im_back:
                finish();
                break;
            case R.id.video_activity_rl_del:
                //删除
                break;
            case R.id.video_activity_im_play:
                //播放
                if (isPlay) {
                    player.pause();
                    stopTimer();
                    isPlay = false;
                    mImPlay.setImageResource(R.mipmap.icon_video_play);
                } else {
                    player.start();

                    stopTimer();
                    startTimer();
                    isPlay = true;
                    mImPlay.setImageResource(R.mipmap.icon_video_stop);
                }
                break;
            case R.id.video_activity_rl_pho:
                Bitmap pho = cutVideo(mVideoPath, player.getCurrentPosition());
                saveMyBitmap(pho, "JPG_" + TimeFormater.dateLongFormatString(System.currentTimeMillis(), TimeFormater.format1));
                showToastLong("截屏已成功");
                break;
            case R.id.video_activity_rl_share:
                //分享
                mLlShare.setVisibility(View.VISIBLE);
                break;
            case R.id.video_activity_btn_cancle:
                //取消分享
                mLlShare.setVisibility(View.GONE);
                break;
        }

    }

    private Bitmap cutVideo(String path, long time) {
        MediaMetadataRetriever media = new MediaMetadataRetriever();
        media.setDataSource(path);
        media.getFrameAtTime(time * 1000 * 1000, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
        Bitmap bitmap = media.getFrameAtTime();

        return bitmap;
    }

    public void saveMyBitmap(Bitmap mBitmap, String bitName) {
        File f = new File(Environment.getExternalStorageDirectory().getPath() + "/" + mApplication.getAppName() + "/photo/" + bitName + ".JPG");
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
        try {
            fOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void shareWX(int Scene) {
        WXFileObject file = new WXFileObject();
        WXMediaMessage msg = new WXMediaMessage();
        String pathVideo = mVideoPath;
        file.setFilePath(pathVideo);
        msg.mediaObject = file;
        //msg.title = "video_demo";
        //msg.description = "微信视频分享";
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("file");
        req.message = msg;
        req.scene = Scene;
        api.sendReq(req);
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis())
                : type + System.currentTimeMillis();
    }

    private void startTimer() {

        if (timer == null) {
            timer = new Timer();
        }

        if (task == null) {
            task = new TimerTask() {
                @Override
                public void run() {
                    //每隔1秒钟执行一下run方法
                    int progress = player.getCurrentPosition();
                    System.out.println("progress" + progress);
                    mSeekBar.setProgress(progress);
                    handler1.sendEmptyMessage(1111);
                }
            };
        }

        if (timer != null && task != null)
            timer.schedule(task, 0, 500);

    }

    private void stopTimer() {

        if (timer != null) {
            timer.cancel();
            timer = null;
        }

        if (task != null) {
            task.cancel();
            task = null;
        }

    }


    @Override
    protected void onDestroy() {
        stopTimer();
        super.onDestroy();
        if (player.isPlaying()) {
            player.stop();
        }
        player.release();
        this.unregisterReceiver(mReceiver);
        //Activity销毁时停止播放，释放资源。不做这个操作，即使退出还是能听到视频播放的声音
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private String calculatTime(int milliSecondTime) {

        int hour = milliSecondTime / (60 * 60 * 1000);
        int minute = (milliSecondTime - hour * 60 * 60 * 1000) / (60 * 1000);
        int seconds = (milliSecondTime - hour * 60 * 60 * 1000 - minute * 60 * 1000) / 1000;

        if (seconds >= 60) {
            seconds = seconds % 60;
            minute += seconds / 60;
        }
        if (minute >= 60) {
            minute = minute % 60;
            hour += minute / 60;
        }

        String sh = "";
        String sm = "";
        String ss = "";
        if (hour < 10) {
            sh = "0" + String.valueOf(hour);
        } else {
            sh = String.valueOf(hour);
        }
        if (minute < 10) {
            sm = "0" + String.valueOf(minute);
        } else {
            sm = String.valueOf(minute);
        }
        if (seconds < 10) {
            ss = "0" + String.valueOf(seconds);
        } else {
            ss = String.valueOf(seconds);
        }

        return sh + ":" + sm + ":" + ss;
    }

    private void firstPlay() {
        player.start();
        mSeekBar.setMax(player.getDuration());
        mTvTime2.setText(calculatTime(player.getDuration()));
        mTvTime1.setText(calculatTime(player.getCurrentPosition()));
        startTimer();
    }


    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        //必须在surface创建后才能初始化MediaPlayer,否则不会显示图像
        player = new MediaPlayer();
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        player.setDisplay(surfaceHolder);
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mSeekBar.setProgress(player.getDuration());
                mTvTime1.setText(calculatTime(player.getDuration()));
                stopTimer();

                isPlay = false;
                mImPlay.setImageResource(R.mipmap.icon_video_play);
            }
        });

        //设置显示视频显示在SurfaceView上
        try {
            player.setDataSource(mVideoPath);
            player.prepare();
        } catch (Exception e) {
            e.printStackTrace();
        }
        firstPlay();

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }

    private Handler handler1 = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1111:
                    mTvTime1.setText(calculatTime(player.getCurrentPosition()));
                    break;
            }
        }
    };
}
